<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use App\Models\Scm\MaterialCategory AS ScmMaterialCategory;   //采购系统物料类型模型
use App\Models\Scm\UnitRelation;                              //采购系统单位模型
use App\Models\Scm\Material AS ScmMaterial;                   //采购系统物料模型
use App\Models\Headquarters\Material AS HQMaterial;           //总部数据模型
use App\Models\Headquarters\MeasureUnit;                      //总部单位模型
use App\Models\Headquarters\MaterialGroup AS HQMaterialGroup; //总部数据模型
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;
use Log;
use App\Notifications\SendEmail;
use App\Models\User;
use PDOException;

class MaterialService
{

    public function syncMaterial($mysql_scm, $sqlsrv)
    {
        try {
            $yestoday = date("Y-m-d H:i:s", time() - 7 * 24 * 60 * 60);
            $scmMaterialCategory = (new ScmMaterialCategory())->setConnection($mysql_scm);
            $scmUnitRelation = (new UnitRelation())->setConnection($mysql_scm);
            $scmMaterial = (new ScmMaterial())->setConnection($mysql_scm);
            $hqMeasureUnit = (new MeasureUnit())->setConnection($sqlsrv);
            $hQMaterialGroup = (new HQMaterialGroup())->setConnection($sqlsrv);
            $datalist = HQMaterial::on($sqlsrv)->where("FCreateTime", ">=", $yestoday)->orWhere('FLastUpdateTime', '>=', $yestoday)->orderBy("FCreateTime", "DESC")->get();
        
            foreach($datalist as $row){
                $hqCategory = $hQMaterialGroup->findRowById($row->FMaterialGroupID);
                $category = $scmMaterialCategory->findRowById($hqCategory->FNumber);
                if($category && $row->FStatus == 1){
                    //查询单位对应关系
                    $hqUnit = $hqMeasureUnit->findRowById($row->FBaseUnit);
                    $transferUnit = $scmUnitRelation->findRowByKingdeeUnit($hqUnit->FNumber);
                    if($transferUnit){
                        $param = array(
                            'name' => $row->FName_L2,
                            'specifi'=> $row->FModel,
                            'unit'=> $transferUnit['unit'],
                            'category_id'=> $hqCategory->FNumber,
                            'status'=> 1,
                            'material_desc'=> $category->name,
                            'kingdee_id' => $row->FID,
                            'kingdee_unit'=> $transferUnit['kingdee_unit'],
                            'kingdee_unit_name'=> $transferUnit['kingdee_unit_name'],
                            'create_time'=> date("Y-m-d H:i:s", strtotime($row->FCreateTime)),
                            'update_time'=> date("Y-m-d H:i:s", strtotime($row->FLastUpdateTime))
                        );

                        //是否已经存在
                        $existObj = $scmMaterial->findRowById($row->FNumber);
                        if(!$existObj){
                            //不存在则新增
                            $param['id'] = $row->FNumber;
                            $param['code'] = $row->FNumber;
                            $param['kingdee_code'] = $row->FNumber;
                            $scmMaterial->insertOne($param);
                        }
                        else{
                            $str1 = md5($param['name'] . $param['specifi'] . $param['unit'] . $param['category_id'] . $param['material_desc'] . $param['kingdee_unit'] . $param['kingdee_unit_name']);
                            $str2 = md5($existObj['name'] . $existObj['specifi'] . $existObj['unit'] . $existObj['category_id'] . $existObj['material_desc'] . $existObj['kingdee_unit'] . $existObj['kingdee_unit_name']);

                            //存在且MD5值不一样则更新
                            if($str1 != $str2){
                                $scmMaterial->updateById($param, $row->FNumber);
                            }
                        }
                    }
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步物料信息异常==========');
            Log::info(var_export($e->getMessage(), true));
            $this->sendEmail("同步物料信息异常", "同步物料信息异常，请注意确认！");
        }
    }

    public function syncMaterialCategory($mysql_scm, $sqlsrv)
    {
        try {
            $yestoday = date("Y-m-d H:i:s", time() - 7 * 24 * 60 * 60);
            $scmMaterialCategory = (new ScmMaterialCategory())->setConnection($mysql_scm);
            $hQMaterialGroup = (new HQMaterialGroup())->setConnection($sqlsrv);
            $datalist = HQMaterialGroup::on($sqlsrv)->where("FCreateTime", ">=", $yestoday)->orderBy("FCreateTime", "DESC")->get();
        
            foreach($datalist as $row){
                //本地采购系统是否存在
                $existObj = $scmMaterialCategory->findRowById($row->FNumber);
                if(!$existObj){
                    $param = array(
                        'id' => $row->FNumber,
                        'name' => $row->FName_L2,
                        'code'=> $row->FNumber,
                        'pid' => 0,
                        'has_child' => "",
                        'status' => "1",
                        'create_time' => date("Y-m-d H:i:s", strtotime($row->FCreateTime)),
                        'kingdee_id' => $row->FID,
                        'kingdee_code' => $row->FNumber
                    );

                    //是否有父节点
                    $hqParent = null;
                    if($row->FParentId){
                        $hqParent = $hQMaterialGroup->findRowById($row->FParentId);
                        if($hqParent){
                            $param['pid'] = $hqParent->FNumber;
                        }
                        else{
                            //父节点并不存在，跳过当前数据
                            continue;
                        }
                    }

                    //是否有子节点  要插入的当前数据是否有子节点
                    $hasChild = $scmMaterialCategory->hasChild($row->FNumber);
                    $param['has_child'] = $hasChild ? 1 : 0;

                    //插入数据
                    $scmMaterialCategory->insertOne($param);

                    //更新父节点的has_child属性
                    if($hqParent && $param['pid']){
                        $scmParent = $scmMaterialCategory->findRowById($param['pid']);
                        if(!$scmParent['has_child']){
                            //只有不为1的时候才更新
                            $scmParent['has_child'] = 1;
                            $scmParent->save();
                        }
                    }
                }
                else{
                    //名称不一致时，更新名称
                    if($existObj->name != $row->FName_L2){
                        $existObj->name = $row->FName_L2;
                        $existObj->save();
                    }
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步物料类型异常==========');
            Log::info(var_export($e->getMessage(), true));
            $this->sendEmail("同步物料类型异常", "同步物料类型异常，请注意确认！");
        }
    }

    public function syncMessureUnit($mysql_scm, $sqlsrv)
    {
        try {
            $scmUnitRelation = (new UnitRelation())->setConnection($mysql_scm);
            $hqMeasureUnit = (new MeasureUnit())->setConnection($sqlsrv);
            $datalist = MeasureUnit::on($sqlsrv)->where("FIsDisabled", "0")->orderBy("FID", "DESC")->get();
        
            foreach($datalist as $row){
                //本地采购系统是否存在
                $existObj = $scmUnitRelation->findRowIfExist($row->FNumber, $row->FName_L2);
                if(!$existObj){
                    $param = array(
                        'kingdee_unit' => $row->FNumber,
                        'kingdee_unit_name' => $row->FName_L2,
                        'del_flag' => 0
                    );

                    //插入数据
                    $scmUnitRelation->insertOne($param);
                }
            }
        } catch (PDOException $e) {
            Log::info('========同步单位异常==========');
            Log::info(var_export($e->getMessage(), true));
        }
    }

    private function sendEmail($title, $content){
        $user = User::find("1");
        $user->notify(new SendEmail($title, $content));
    }
}
